package org.example.product.controller;
import org.example.product.entity.ResultBody;
import org.example.product.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/SearchGoods")
@CrossOrigin(origins="*")
public class SearchController {
    @Autowired
    private SearchService searchService;
    @RequestMapping("/searchGoods")
    public ResultBody searchGoods(@RequestBody Map<String,Object>map) {
        //判断参数是否完整
        if (map.get("name") == null) {
            return new ResultBody(404, "缺少参数", false);
        }
        //当按照名字时
            String name = (String) map.get("name");
            if(name.equals("粮食类") || name.equals("水果类")||name.equals("蔬菜类") ||name.equals("畜牧产品")||name.equals("水产类"))
            {
                String kind = name;
                List<Map<String, Object>> list = searchService.searchByKind(kind);
                if (list != null) {
                    return new ResultBody(200, "搜索成功", list, list.size());
                } else
                    return new ResultBody(400, "未搜索到", false);
            }
            List<Map<String, Object>> list = searchService.searchByName(name);
            if (list != null) {
                return new ResultBody(200, "搜索成功", list, list.size());
            } else
                return new ResultBody(400, "未搜索到", false);
        }

        @RequestMapping("/searchGoodsByPrice")
        public ResultBody searchGoodsByKind(@RequestBody Map<String,Object>map) {
            if (map.get("minprice") == null|| map.get("maxprice") == null) {
                return new ResultBody(404, "缺少参数", false);
            }
            Object objectmin= map.get("minprice");
            Object objectmax= map.get("maxprice");
            double minprice ;
            double maxprice ;
            if(objectmin instanceof Integer&& objectmax instanceof Integer)
            {
                minprice = (Integer)objectmin;
                maxprice = (Integer)objectmax;
            }
            else if(objectmin instanceof Double&& objectmax instanceof Double)
            {
                minprice = (Double)objectmin;
                maxprice = (Double)objectmax;
            }
            else if (objectmin instanceof String&& objectmax instanceof String)
            {
                minprice = Double.parseDouble((String)objectmin);
                maxprice = Double.parseDouble((String)objectmax);
            }
            else
                return new ResultBody(400,"参数类型错误",false);

            return searchService.searchGoodsByPrice(minprice,maxprice);
        }

    }
